﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using SharedLib.XmlDataModel;
using Tracy.DataModel;
using SharedLib.Helpers;

namespace Tracy.DataServices
{
    public class SearchEngine
    {
        private Dictionary<string, Resource> _resourceSearchResult = new Dictionary<string, Resource>();

        public List<Resource> ResourceSearchResult
        {
            get { return _resourceSearchResult.Values.ToList(); }
        }


        private Dictionary<string, MediaFile> _fileSearchResult = new Dictionary<string, MediaFile>();
        public List<MediaFile> FileSearchResult
        {
            get { return _fileSearchResult.Values.ToList(); }
        }

        private string _lastSearchKeyword = null;
        public void Search(string keyword)
        {
            string unifiedKeyword = StringHelper.UnifyStringFormat(keyword);
            List<Resource> resList;
            List<MediaFile> fileList;
            if (_lastSearchKeyword != null && unifiedKeyword.Contains(_lastSearchKeyword))
            {
                resList = ResourceSearchResult;
                fileList = FileSearchResult;
            }
            else
            {
                resList = TracyFacade.Instance.ResourceProvider.GetItems();
                fileList = TracyFacade.Instance.MediaFileProvider.GetItems();
            }
            _resourceSearchResult.Clear();
            _fileSearchResult.Clear();
            Search(unifiedKeyword, resList, fileList);
        }

        private void Search(string keyword, List<Resource> resList, List<MediaFile> fileList)
        {
            foreach (Resource res in resList)
            {
                if (StringHelper.UnifyStringFormat(res.Title).Contains(keyword))
                {
                    if(!_resourceSearchResult.ContainsKey(res.ID)) _resourceSearchResult.Add(res.ID, res);
                    foreach (MediaFile file in TracyFacade.Instance.MediaFileProvider.GetItemByResource(res))
                    {
                        if (!_fileSearchResult.ContainsKey(file.ID)) _fileSearchResult.Add(file.ID, file);
                    }
                }
            }
            foreach (MediaFile file in fileList)
            {
                if (StringHelper.UnifyStringFormat(file.FileName).Contains(keyword))
                {
                    if(!_fileSearchResult.ContainsKey(file.ID)) _fileSearchResult.Add(file.ID, file);
                    if (!_resourceSearchResult.ContainsKey(file.Resource.ID)) _resourceSearchResult.Add(file.Resource.ID, file.Resource);
                }
            }
            _lastSearchKeyword = keyword;
        }
    }
}
